//
//  RKKeepAlive.m
//  WuyouTang
//
//  Created by YB007 on 2020/7/22.
//  Copyright © 2020 cat. All rights reserved.
//

#import "RKKeepAlive.h"
#import "AppDelegate.h"

static RKKeepAlive *_keepInstance = nil;

@interface RKKeepAlive(){
    int vvvv;
    NSTimer *_timer;
}
@property (nonatomic, assign) UIBackgroundTaskIdentifier backgroundTaskIdentifier;
@end
@implementation RKKeepAlive

+(instancetype)sharedKeepInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _keepInstance = [[super allocWithZone:NULL]init];
    });
    return _keepInstance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    return [self sharedKeepInstance];
}

- (void)initPlayer {
    [self.player prepareToPlay];
}
- (AVAudioPlayer *)player {
    if (!_player) {
        NSError *error = nil;
        NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"mute-mp3" withExtension:@"mp3"];
        AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
        audioPlayer.numberOfLoops = NSUIntegerMax;
        _player = audioPlayer;
        NSLog(@"%s 初始化==:%@",__FUNCTION__,error);
    }
    return _player;
}

-(void)startAppLifeCycleMonitor{
    self.needKeepAliveInBackground = YES;
    YBWeakSelf;
    AppDelegate *appDelegate =  (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.lifeCycleEvent = ^(YBAppLifeCycle lifeCycleType) {
        [weakSelf appDelegateBlockEvent:lifeCycleType];
    };
}
-(void)appDelegateBlockEvent:(YBAppLifeCycle)lifeCycleType {
    switch (lifeCycleType) {
        case APPLifeCycle_EnterForeground:{
            //[self appActive];
            //前台
            NSLog(@"%s：应用将进入前台WillEnterForeground", __FUNCTION__);
            if (self.needKeepAliveInBackground) {
                [self.player pause];
            }
            [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
        }break;
        case APPLifeCycle_EnterBackground:{
            //[self backGround];
            //后台
            self.backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithName:kBgTaskName expirationHandler:^{
                if (self.needKeepAliveInBackground) {
                    [self.player play];
                }
                if (self.backgroundTaskIdentifier != UIBackgroundTaskInvalid) {
                    [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
                    self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
                }
            }];
            NSLog(@"%s：应用进入后台DidEnterBackground", __FUNCTION__);
        }break;
        case APPLifeCycle_WillTerminate:{
            //杀进程
            NSLog(@"%s：应用终止：WillTerminate", __FUNCTION__);
        }break;
            
        default:
            break;
    }
}
#pragma mark - 保活测试
-(void)backGround {
    [self setupTimer];
}
-(void)appActive {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
        vvvv = 0;
    }
}

#pragma mark - 定时器
- (void)setupTimer {
    vvvv = 1;
    
    _timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerEvent:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    [_timer fire];
}

- (void)timerEvent:(id)sender {
    vvvv ++;
    NSLog(@"普通定时器运行中:%d",vvvv);
    
    if (vvvv%60 == 0) {
        [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%d",vvvv] forKey:@"rk_keep_alive_time"];
    }
}

@end
